<?php
namespace dgwht\sms;
use GuzzleHttp\Client as HttpClient;

class Ali {
    private $Config;
 
    function __construct($config = []) {
		//AccessKey ID
        $this->Config['id'] = isset($config['id']) ? $config['id'] : '';
		//AccessKey Secret
        $this->Config['key'] = isset($config['key']) ? $config['key'] : '';
		//签名
        $this->Config['sign'] = isset($config['sign']) ? $config['sign'] : '';
		//模板ID
        $this->Config['tpl'] = isset($config['tpl']) ? $config['tpl'] : '';
    }
	
    public function send($phone='', $data=[]) {
		try{
			$data = $this->getData($phone, $data);
			$url = $this->getUrl($data);
			
            $httpClient = new HttpClient();
            $response = $httpClient->request('GET', $url, ['json' => $httpData]);
			$ret = $response->getBody()->getContents();
			
			$ret = json_decode( $ret, true );
		}catch(Exception $e) {
			return $e;
		}
		if($ret[ "Message" ] != 'OK'){
		    return $ret[ "Message" ];
		}
		return true;
    }
	
	private function getData($phone, $data) {
		$params = array(
			'SignName' => $this->Config['sign'],
			'Format' => 'JSON',
			'Version' => '2017-05-25',
			'AccessKeyId' => $this->Config['id'],
			'SignatureVersion' => '1.0',
			'SignatureMethod' => 'HMAC-SHA1',
			'SignatureNonce' => uniqid(),
			'Timestamp' => gmdate( 'Y-m-d\TH:i:s\Z' ),
			'Action' => 'SendSms',
			'TemplateCode' => $this->Config['tpl'],
			'PhoneNumbers' => $phone,
			'TemplateParam' => json_encode( $data, JSON_UNESCAPED_UNICODE )
		);
		$params[ 'Signature' ] = $this->computeSignature( $params, $this->Config['key'] );
		return $params;
	}
	
    private function computeSignature($parameters, $accessKeySecret) {
        ksort ( $parameters );
        $canonicalizedQueryString = '';
        foreach ( $parameters as $key => $value ) {
            $canonicalizedQueryString .= '&' . $this->percentEncode ( $key ) . '=' . $this->percentEncode ( $value );
        }
        $stringToSign = 'GET&%2F&' . $this->percentEncode ( substr ( $canonicalizedQueryString, 1 ) );
        $signature = base64_encode ( hash_hmac ( 'sha1', $stringToSign, $accessKeySecret . '&', true ) );
        return $signature;
    }
 
    private function percentEncode($string) {
        $string = urlencode ( $string );
        $string = preg_replace ( '/\+/', '%20', $string );
        $string = preg_replace ( '/\*/', '%2A', $string );
        $string = preg_replace ( '/%7E/', '~', $string );
        return $string;
    }
	
	private function getUrl($data){
		$url = 'http://dysmsapi.aliyuncs.com/?' . http_build_query($data);
		return $url;
	}
	
	private function http($url){
		$ch = curl_init();
    	curl_setopt( $ch, CURLOPT_URL, $url );
    	curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, FALSE );
    	curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, FALSE );
    	curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
    	curl_setopt( $ch, CURLOPT_TIMEOUT, 10 );
    	$res = curl_exec( $ch );
    	curl_close( $ch );
		return $res;
	}
	
}

